/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import db.MysqlAdapter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.met.metdata.proxy.MetServiceProxy;
import no.met.metdata.proxy.no_met_metdata_StationProperties;

/**
 * <p> servlet håndterer forskjellige operasjoner
 *
 * @author 490501
 */
public class AjaxHandler extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s = request.getParameter("mode");
        if (s != null && s.equals("profile")) {
            //håndterer ny profil
            MysqlAdapter ms = new MysqlAdapter();
            String type = request.getParameter("type");
            String name = request.getParameter("name");
            String values = request.getParameter("values");
            int userID = (Integer) request.getSession().getAttribute("id");
            if (type.equals("lighting")) {
                try {
                    ms.addUsageProfile(name, type, values, userID);
                    return;
                } catch (Exception ex) {
                    Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (type.equals("equip")) {
                try {
                    ms.addUsageProfile(name, type, values, userID);
                    return;
                } catch (Exception ex) {
                    Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else if (s != null && s.equals("getfylke")) {
            try {
                response.setContentType("application/json");
                MysqlAdapter ms = new MysqlAdapter();
                HashMap<Integer, String> hm = ms.getFylker();
                Set _temp = hm.entrySet();
                String _result = "{";
                for (Iterator it = _temp.iterator(); it.hasNext();) {
                    Entry en = (Entry) it.next();
                    _result += " \"" + en.getKey() + "\":\"" + en.getValue() + "\",";
                }
                _result = _result.substring(0, _result.length() - 1);
                _result += "}";
                PrintWriter writer = response.getWriter();
                writer.println(_result);
                writer.flush();
                writer.close();
                return;
            } catch (SQLException ex) {
                Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(503);
            }

        } else if (s != null && s.equals("getkommune")) {
            String fylkeId = request.getParameter("fylkeid");
            int id = Integer.valueOf(fylkeId.substring(7));
            try {
                response.setContentType("application/json");
                MysqlAdapter ms = new MysqlAdapter();
                HashMap<Integer, String> hm = ms.getKommuner(id);
                Set _temp = hm.entrySet();
                String _result = "{";
                for (Iterator it = _temp.iterator(); it.hasNext();) {
                    Entry en = (Entry) it.next();
                    _result += " \"" + en.getKey() + "\":\"" + en.getValue() + "\",";
                }
                _result = _result.substring(0, _result.length() - 1);
                _result += "}";
                PrintWriter writer = response.getWriter();
                writer.println(_result);
                writer.flush();
                writer.close();
                return;
            } catch (SQLException ex) {
                Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(503);
            }
        } else if (request.getParameter("mode").equals("getpatternnames")) {
            try {
                getUsagePatternNames(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(503);
            }
        } else if (request.getParameter("mode").equals("getusageprofile")) {
            try {
                getUsagePatternByName(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (s != null && s.equals("getprofilelist")) {
            int userID = (Integer) request.getSession().getAttribute("id");
            //String type = request.getParameter("type");
            MysqlAdapter ms = new MysqlAdapter();
            try {
                response.setContentType("application/json");
                HashMap<Integer, String> hm = ms.getUsageProfiles(userID);
                Set _temp = hm.entrySet();
                String _result = "{";
                for (Iterator it = _temp.iterator(); it.hasNext();) {
                    Entry en = (Entry) it.next();
                    _result += " \"" + en.getKey() + "\":\"" + en.getValue() + "\",";
                }
                _result = _result.substring(0, _result.length() - 1);
                _result += "}";
                PrintWriter writer = response.getWriter();
                writer.println(_result);
                writer.flush();
                writer.close();
                return;
            } catch (SQLException ex) {
                Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(503);
            }

        } else if (s != null && s.equals("getStations")) {
            getStationsForKommune(request, response);
            return;
        }
        response.sendError(501);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * *
     *
     * @param request
     * @param response
     * @throws SQLException
     * @throws IOException
     */
    public void getUsagePatternNames(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String _type = request.getParameter("type");
        MysqlAdapter ms = new MysqlAdapter();
        int userID = (Integer) request.getSession().getAttribute("id");
        ArrayList<String> res = ms.getUsagePatternNames(_type, userID);
        response.setContentType("application/json");
        String _result = "{";
        int i = 0;
        for (String s : res) {
            _result += "\"name" + i++ + "\":" + "\"" + s + "\",";  // "\"name\":\"" + s + "\",";
        }
        _result = _result.substring(0, _result.length() - 1);
        _result += "}";
        PrintWriter writer = response.getWriter();
        writer.println(_result);
        writer.flush();
        writer.close();
    }

    public void getUsagePatternByName(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        String name = request.getParameter("name");
        String type = request.getParameter("type");
        MysqlAdapter ms = new MysqlAdapter();
        String values = ms.getUsagePattern(type, name);
        //lager JSON
        String _result = "{\"name\":\"" + name + "\",\"type\":\"" + type + "\",\"data\":[" + values + "]}";
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.println(_result);
        writer.flush();
        writer.close();
    }

    /**
     * <p>return meteorologiske stasjoner til gitt kommune
     *
     * @param request
     * @param response
     */
    private void getStationsForKommune(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int kommuneId = Integer.valueOf(request.getParameter("kommuneNr"));
        MetServiceProxy mt = new MetServiceProxy();
        no_met_metdata_StationProperties[] st = null;
        try {
            st = mt.getStationsProperties(null, null);
        } catch (Exception ex) {
            Logger.getLogger(AjaxHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        String result = "{ \"stations\":[";
        for (int i = 0; i < st.length; i++) {
            if (st[i].getMunicipalityNo() == kommuneId) {
                result += "{\"stationName\":\"" + st[i].getName() + "\"},";
            }

        }
        result = result.substring(0, result.length() - 1);
        result += "]}";
        System.out.println(result);
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.println(result);
        writer.flush();
        writer.close();
    }
}
